import RequestManager from './requestManager.js'

const BASE_URL = 'https://bp.api.10417.com/';
// const BASE_URL = 'http://api.taoqiyou.com:17486/';

const manager = new RequestManager()

const baseRequest = async (url, method, data = {}, loading = true) => {
	let requestId = manager.generateId(method, url, data)
	if (!requestId) {
		console.log('重复请求')
	}
	if (!requestId) return false;

	const header = {}
	header.Authorization = uni.getStorageSync('token') || '';

	let loadingPromise = loading ? new Promise((resolve) => {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		resolve()
	}) : Promise.resolve()

	return Promise.all([
		loadingPromise,
		new Promise((resolve, reject) => {
			uni.request({
				url: BASE_URL + url,
				method: method || 'GET',
				header: header,
				timeout: 30000,
				data: data || {},
				complete: () => {
					manager.deleteById(requestId)
				},
				success: (response) => {
					const result = response.data
					if (response.statusCode == 200) {
						if (result.code != 200) {
							uni.showToast({
								title: result.msg,
								icon: 'none'
							})
							reject(result)
						} else {
							resolve(result)
						}
					} else {
						uni.showToast({
							title: '网络连接失败，请稍后重试1',
							icon: 'none'
						})
						reject(result)
					}
				},
				fail: (msg) => {
					uni.showToast({
						title: '网络连接失败，请稍后重试2',
						icon: 'none'
					})
					reject(msg)
				}
			})
		})
	]).finally(() => {
		uni.hideLoading()
	});
}


const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
})



export default request